import 'package:flutter/material.dart';
import 'package:znmm/UI/utils/my_global.dart';
import 'package:znmm/config/app_asset.dart';

import 'attributes_model.dart';

class ProductModel {
  String icon = AppAsset.chart01; //icon
  int quantity = 0; //数量
  //自定义产品类型 newProducts / featuredProducts / bestSellingProducts
  int iProductType = 0;
  List<String> imagesList = [
    AppAsset.chart01,
    AppAsset.chart02,
    AppAsset.chart03,
    AppAsset.chart04,
    AppAsset.chart05,
    AppAsset.comhar,
  ];
  List<ProductColorModel> colorsList = <ProductColorModel>[
    ProductColorModel(color: const Color(0xFF616161), isSelected: true),
    ProductColorModel(color: const Color.fromARGB(255, 71, 70, 131)),
    ProductColorModel(color: const Color.fromARGB(255, 202, 86, 86)),
  ]; //颜色选择

  bool bIsFavorite = false; //爱心

  //--------------------真实服务器下发
  int databaseId = 0; //
  String name = "---name---"; //name
  String slug = "---slug---"; //slug
  String description = '---description---'; // 描述
  String sourceUrl = ''; // sourceUrl

  double averageRating = 0; //星星评分
  String price = "0"; //价格
  String regularPrice = "0"; //常规价格
  String stockStatus = "..."; //库存状态
  int stockQuantity = 0;

  String shortDescription = "";
  String salePrice = "0";
  List<String> galleryImagesList = [];

  String title = "---title---"; //标题
  String date = "---date---";
  String content = "---content---";
  String featuredImage = "";

  //webview link (PRODUCTBYSLUG_QUERY 接口)
  String link = "";
  String productCateName = "";
  List<AttributesModel> attriModelList = []; //attributes Model
  List<VariationsModel> variaModelList = []; //VariationsModel Model

  ///-----------------------------
  String discount = ""; //百分比 折扣
  String detail = ""; //详情
  double score = 0; //评分
  List<ProductColorModel> colors = []; //颜色选择
  bool isFavorite = false; //❤️

  //--------------------
  ProductModel({
    this.title = '---',
    this.price = "0",
    this.icon = AppAsset.cups,
    this.description = "---",
    this.quantity = 1,
    this.iProductType = 0,
    this.imagesList = const [],
    this.colorsList = const [],
    this.date = "---date---",
    this.content = "---content---",
    this.featuredImage = "",
    this.link = "",
    this.attriModelList = const [],
    this.variaModelList = const [],
    this.productCateName = "",
    this.databaseId = 0,
    this.slug = "---slug---",
    this.sourceUrl = "",
    this.averageRating = 0,
    this.regularPrice = "0",
    this.stockStatus = "",
    this.stockQuantity = 0,
    this.shortDescription = "",
    this.salePrice = "0",
    this.galleryImagesList = const [],
    this.bIsFavorite = false,
    this.name = "---name---",

    ///--------------------
    this.isFavorite = false,
    this.colors = const [],
    this.score = 0,
    this.discount = "",
    this.detail = "",
  });

  ProductModel.fromJson(Map<String, dynamic> json) {
    databaseId = MyGlobal.checkNullOrZero(json['databaseId']);
    name = MyGlobal.checkNullOrEmpty(json['name']);
    int iAverage = MyGlobal.checkNullOrZero(json['averageRating']);
    averageRating = iAverage.toDouble();
    slug = MyGlobal.checkNullOrEmpty(json['slug']);
    var imageJson = json['image'];
    if (imageJson != null) {
      sourceUrl =
          MyGlobal.checkNullOrEmpty(imageJson['sourceUrl'], strRetun: "");
    }

    price = MyGlobal.checkNullOrEmpty(json['price'], strRetun: "0");
    regularPrice = MyGlobal.checkNullOrEmpty(json['regularPrice']);
    stockStatus = MyGlobal.checkNullOrEmpty(json['stockStatus']);
    stockQuantity = MyGlobal.checkNullOrZero(json['stockQuantity']);

    var galleryImagesVal = json["galleryImages"];
    if (galleryImagesVal != null) {
      var nodesList = galleryImagesVal['nodes'] as List;
      for (int iIndex = 0; iIndex < nodesList.length; iIndex++) {
        String urtStr = nodesList[iIndex]["sourceUrl"];
        galleryImagesList.add(urtStr);
      }
    }

    //description = MyGlobal.checkNullOrEmpty(json['description']);
  }

  //shopping 购物页面
  ProductModel.fromJson2(Map<String, dynamic> json) {
    var edgesList = json['products']['edges'] as List;
    if (edgesList.isEmpty) return;
    var edgesNodeJson = edgesList[0]["node"];

    if (edgesNodeJson == null) return;
    databaseId = MyGlobal.checkNullOrZero(edgesNodeJson['databaseId']);

    //name
    String nameStr = edgesNodeJson["name"] ?? "";
    //print("nameStr:$nameStr");
    name = nameStr;
    //description
    String descriptionStr = edgesNodeJson["description"] ?? "";
    //print("descriptionStr:$descriptionStr");
    description = descriptionStr;

    //link
    String linkStr = edgesNodeJson["link"] ?? "";
    //print("linkStr:$linkStr");
    link = linkStr;

    //price
    String priceStr = edgesNodeJson["price"] ?? "0";
    //print("priceStr:$priceStr");
    price = priceStr;

    stockStatus = MyGlobal.checkNullOrEmpty(edgesNodeJson['stockStatus']);
    stockQuantity = MyGlobal.checkNullOrZero(edgesNodeJson['stockQuantity']);

    //attributes
    if (edgesNodeJson["attributes"] != null) {
      var attriNodesList = edgesNodeJson["attributes"]['nodes'] as List;
      for (int iIndex = 0; iIndex < attriNodesList.length; iIndex++) {
        var attributesJson = attriNodesList[iIndex];
        attriModelList.add(AttributesModel.fromJson(attributesJson));
      }
    }

    //variaModel
    if (edgesNodeJson["variations"] != null) {
      var variaNodesList = edgesNodeJson["variations"]['nodes'] as List;
      for (int iIndex = 0; iIndex < variaNodesList.length; iIndex++) {
        var variaJson = variaNodesList[iIndex];
        variaModelList.add(VariationsModel.fromJson(variaJson));
      }
    }

    //galleryImagesList
    if (edgesNodeJson["galleryImages"] != null) {
      galleryImagesList.clear();

      var nodesList = edgesNodeJson["galleryImages"]['nodes'] as List;
      for (int iIndex = 0; iIndex < nodesList.length; iIndex++) {
        var nodeJson = nodesList[iIndex];
        String sourceUrl = nodeJson["sourceUrl"];
        //print("sourceUrl:$sourceUrl");
        galleryImagesList.add(sourceUrl);
      }
    }
    //productCateName
    if (edgesNodeJson["productCategories"] != null) {
      var edgesList1 = edgesNodeJson["productCategories"]['edges'] as List;

      for (int iedgCount = 0; iedgCount < edgesList1.length; iedgCount++) {
        var produName = edgesList1[iedgCount]["node"]["name"];
        //print("produName:$produName");
        productCateName = "${productCateName + produName} ";
      }
    }
  }

  //VariationsModel
  VariationsModel? findVariationByTagKey(String tgKey, bool bIsSelAl) {
    VariationsModel? foundVariation;
    try {
      foundVariation =
          variaModelList.firstWhere((element) => element.tagKey == tgKey);
    } catch (e) {
      foundVariation = null;
    }

    if (variaModelList.isNotEmpty && foundVariation == null && bIsSelAl) {
      foundVariation = variaModelList[0];
    }

    return foundVariation;
  }

  //--------------------------copy
  ProductModel copyWith({
    double? star,
    int? sold,
    String? icon,
    int? quantity,
    int? iProductType,
    double? score,
    List<String>? imagesList,
    bool? isFavorite,
    List<ProductColorModel>? colorsList,
    String? discount,
    String? detail,
    String? title,
    String? date,
    String? content,
    String? featuredImage,
    String? link,
    String? plugTypeStr,
    List<AttributesModel>? attriModelList,
    List<VariationsModel>? variaModelList,
    Map<String, List<String>>? variationsMap,
    Map<String, VariationsModel>? tagSelectVariaMap,
    bool? bIsVariations,
    List<String>? plugTypeList,
    String? colorTypeStr,
    List<String>? colorTypeList,
    String? productCateName,
    String? id,
    int? databaseId,
    String? slug,
    String? description,
    String? sourceUrl,
    double? averageRating,
    String? price,
    String? regularPrice,
    String? stockStatus,
    int? stockQuantity,
    String? shortDescription,
    String? salePrice,
    List<String>? galleryImagesList,
    bool? bIsFavorite,
    String? name,
  }) {
    return ProductModel(
      icon: icon ?? this.icon,
      quantity: quantity ?? this.quantity,
      iProductType: iProductType ?? this.iProductType,
      imagesList: imagesList ?? this.imagesList,
      colorsList: colorsList ?? this.colorsList,
      title: title ?? this.title,
      date: date ?? this.date,
      content: content ?? this.content,
      featuredImage: featuredImage ?? this.featuredImage,
      link: link ?? this.link,
      attriModelList: attriModelList ?? this.attriModelList,
      variaModelList: variaModelList ?? this.variaModelList,
      productCateName: productCateName ?? this.productCateName,
      databaseId: databaseId ?? this.databaseId,
      slug: slug ?? this.slug,
      description: description ?? this.description,
      sourceUrl: sourceUrl ?? this.sourceUrl,
      averageRating: averageRating ?? this.averageRating,
      price: price ?? this.price,
      regularPrice: regularPrice ?? this.regularPrice,
      stockStatus: stockStatus ?? this.stockStatus,
      stockQuantity: stockQuantity ?? this.stockQuantity,
      shortDescription: shortDescription ?? this.shortDescription,
      salePrice: salePrice ?? this.salePrice,
      galleryImagesList: galleryImagesList ?? this.galleryImagesList,
      bIsFavorite: bIsFavorite ?? this.bIsFavorite,
      name: name ?? this.name,
    );
  }
}

//商品颜色model
class ProductColorModel {
  Color color;
  bool isSelected;

  ProductColorModel({required this.color, this.isSelected = false});
}




/*
"newProducts"

{
  "__typename": "RootQueryToProductUnionConnectionEdge",
  "node": {
    "__typename": "VariableProduct",
    "databaseId": 630,
    "name": "CNUS X3Art - Luxury Waterless Diffuser with Custom Logo Perfume for Car and Home",
    "averageRating": 0,
    "slug": "cnus-x3art-luxury-waterless-diffuser-with-custom-logo-perfume-for-car-and-home-2",
    "image": {
      "__typename": "MediaItem",
      "sourceUrl": "https://react.scentsin.com/wp-content/uploads/2024/02/Hcb23c5f356c74273a4d04e724d95a9dbg.webp"
    },
    "price": "$39.99",
    "regularPrice": "$39.99",
    "stockStatus": "IN_STOCK",
    "galleryImages": {
      "__typename": "ProductToMediaItemConnection",
      "nodes": [
        {
          "__typename": "MediaItem",
          "sourceUrl": "https://react.scentsin.com/wp-content/uploads/2024/04/2-1.jpg"
        },
        {
          "__typename": "MediaItem",
          "sourceUrl": "https://react.scentsin.com/wp-content/uploads/2024/04/9-1.png"
        },
        {
          "__typename": "MediaItem",
          "sourceUrl": "https://react.scentsin.com/wp-content/uploads/2024/04/8.jpg"
        },
        {
          "__typename": "MediaItem",
          "sourceUrl": "https://react.scentsin.com/wp-content/uploads/2024/04/4.png"
        },
        {
          "__typename": "MediaItem",
          "sourceUrl": "https://react.scentsin.com/wp-content/uploads/2024/04/7.png"
        },
        {
          "__typename": "MediaItem",
          "sourceUrl": "https://react.scentsin.com/wp-content/uploads/2024/04/9-2.png"
        },
        {
          "__typename": "MediaItem",
          "sourceUrl": "https://react.scentsin.com/wp-content/uploads/2024/04/3-1.jpg"
        }
      ]
    }
  }
},


*/
